package cn.nextProject.Utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.Base64;

@Slf4j
public class AESUtils {
    // 加密算法和数据库连接配置
    private static final String ALGORITHM = "AES/CBC/PKCS5Padding"; //定义加密模式
    private static final int KEY_SIZE = 128; // 密钥长度
    private static final byte[] IV = new byte[16]; // 初始化向量 (IV)，实际应用中应随机生成并保存


    // 生成 AES 密钥
    public static SecretKey generateAESKey() throws Exception {
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES"); //密钥模式选择AES
        keyGenerator.init(KEY_SIZE,new SecureRandom()); //密钥长度
        return keyGenerator.generateKey(); //生成密钥
    }

    // 使用 AES 密钥加密密码
    public static String encryptPassword(String password, SecretKey secretKey) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM); //初始化加密算法
        IvParameterSpec ivSpec = new IvParameterSpec(IV);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivSpec);//放入密钥
        byte[] encryptedBytes = cipher.doFinal(password.getBytes(StandardCharsets.UTF_8));//生成密码数组
        return Base64.getEncoder().encodeToString(encryptedBytes);//转换为十六进制字符串并返回
    }

    // 使用 AES 密钥解密密码
    public static String decryptPassword(String encryptedPassword, SecretKey secretKey) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM);//初始化解密算法
        IvParameterSpec ivSpec = new IvParameterSpec(IV); // 设置初始化向量
        cipher.init(Cipher.DECRYPT_MODE, secretKey,ivSpec); //放入密钥
        byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedPassword));//解密
        return new String(decryptedBytes, StandardCharsets.UTF_8); //返回解密后的密码
    }

    // 测试方法
    public static void main(String[] args) {
        try {
            String oldPassword = "zxfcasdas";
            SecretKey secretKey = generateAESKey();

            // 加密
            String realPassword = encryptPassword(oldPassword, secretKey);
            log.info("加密后的密码: {}", realPassword);

            // 解密
            String decryptedPassword = decryptPassword(realPassword, secretKey);
            log.info("解密后的密码: {}", decryptedPassword);

        } catch (Exception e) {
            log.error("加密解密失败", e);
        }
    }


}